import 'dart:convert' show json;

import 'package:loxen/mode/user.dart';

T asT<T>(dynamic value) {
  if (value is T) {
    return value;
  }

  return null;
}

class Comment {
  Comment({
    this.user,
    this.likes_num,
    this.sub_comment,
    this.is_like,
    this.add_time,
    this.id,
    this.sub_comment_num,
    this.content,
  });

  factory Comment.fromJson(Map<String, dynamic> jsonRes) {
    if (jsonRes == null) {
      return null;
    }

    final List<Comment> sub_comment =
        jsonRes['sub_comment'] is List ? <Comment>[] : null;
    if (sub_comment != null) {
      for (final dynamic item in jsonRes['sub_comment']) {
        if (item != null) {
          sub_comment.add(Comment.fromJson(asT<Map<String, dynamic>>(item)));
        }
      }
    }
    return Comment(
      user: User.fromJson(asT<Map<String, dynamic>>(jsonRes['user'])),
      likes_num: asT<int>(jsonRes['likes_num']),
      sub_comment: sub_comment,
      is_like: asT<int>(jsonRes['is_like']),
      add_time: asT<String>(jsonRes['add_time']),
      id: asT<int>(jsonRes['id']),
      sub_comment_num: asT<int>(jsonRes['sub_comment_num']),
      content: asT<String>(jsonRes['content']),
    );
  }

  User user;
  int likes_num;
  List<Comment> sub_comment;
  int is_like;
  String add_time;
  int id;
  int sub_comment_num;
  String content;
  int subPage = 1;

  Map<String, dynamic> toJson() => <String, dynamic>{
        'user': user,
        'likes_num': likes_num,
        'sub_comment': sub_comment,
        'is_like': is_like,
        'add_time': add_time,
        'id': id,
        'sub_comment_num': sub_comment_num,
        'content': content,
      };

  @override
  String toString() {
    return json.encode(this);
  }
}
